#include "options.h"

Options::Options(QString configFile, QObject *parent) :
        QObject(parent)
{
    config = new QSettings(configFile, QSettings::IniFormat);
    dialog = new OptionsDialog();
    connect(dialog, SIGNAL(saveSettings()), this, SLOT(reloadFromGui()));
}

Options::~Options()
{
    config->sync();
    delete config;
}

void Options::updateValues(QString email, QString password)
{
    bool b = false;
    if (email != "")
    {
        settings.email = email;
        b = true;
    }
    if (password != "")
    {
        settings.password = password;
        b = true;
    }
    if (b)
        save();
}

void Options::load()
{
    settings.email = config->value("auth/email", "").toString();
// TODO: add encryption here
    settings.password = config->value("auth/password", "").toString();
    settings.checkTime = config->value("misc/time", 20).toInt();
    settings.useProxy = config->value("proxy/use", false).toBool();
    settings.proxyHost = config->value("proxy/host", "").toString();
    settings.proxyPort = config->value("proxy/port", 3128).toInt();
    settings.useProxyAuth = config->value("proxy/useauth", false).toBool();
    settings.proxyUser = config->value("proxy/user", "").toString();
    settings.proxyPass = config->value("proxy/password", "").toString();
    emit optionsChanged();
}

void Options::save()
{
    config->setValue("auth/email", settings.email);
    config->setValue("auth/password", settings.password);
    config->setValue("misc/time", settings.checkTime);
    config->setValue("proxy/use", settings.useProxy);
    config->setValue("proxy/host", settings.proxyHost);
    config->setValue("proxy/port", settings.proxyPort);
    config->setValue("proxy/useauth", settings.useProxyAuth);
    config->setValue("proxy/user", settings.proxyUser);
    config->setValue("proxy/password", settings.proxyPass);
    config->sync();
}

void Options::showDialog()
{
    updateGui();
    dialog->show();
}

void Options::updateGui()
{
    dialog->setEmail(settings.email);
    dialog->setPassword(settings.password);
    dialog->setTimeout(settings.checkTime);
    dialog->setUseProxy(settings.useProxy);
    dialog->setProxyHost(settings.proxyHost);
    dialog->setProxyPort(settings.proxyPort);
    dialog->setUseProxyAuth(settings.useProxyAuth);
    dialog->setProxyUser(settings.proxyUser);
    dialog->setProxyPassword(settings.proxyPass);
    dialog->updateActive();
}

void Options::reloadFromGui()
{
    settings.email = dialog->getEmail();
    settings.password = dialog->getPassword();
    settings.checkTime = dialog->getTimeout();
    settings.useProxy = dialog->getUseProxy();
    settings.proxyHost = dialog->getProxyHost();
    settings.proxyPort = dialog->getProxyPort();
    settings.useProxyAuth = dialog->getUseProxyAuth();
    settings.proxyUser = dialog->getProxyUser();
    settings.proxyPass = dialog->getProxyPassword();
    save();
    emit optionsChanged();
}
